import { defineStore } from "pinia";

import { post, treeToList } from '../utils';
import { constRoutes } from '../router';
import { state } from "@antv/g2plot/lib/adaptor/common";

export const userStore = defineStore('user', {
	state: () => ({
		info: {},
		routes: []
	}),

	getters: {
		getInfo(state) {
			return state.info;
		}
	},

	actions: {
		async setInfo() {
			const userInfo = await post('user/profile');

			this.info = userInfo;
		},

		async setRoutes() {
			//const { modules } = await post('user/profile');
			const { modules } = this.info || {};

			const routes = [];
			//动态生成路由
			for (const { title, icon, id: key, children = [] } of modules) {

				const route = {
					path: '/',
					component: () => import('@/views/Index'),
					meta: { title, icon, key },
					children: []
				}

				if (routes.length === 0) {
					route.redirect = '/dashboard';
				}
				route.children = (treeToList(children) || []).filter((d) => d.type === 1 && d.name).map((d) => {
					const { path, component, name, title, id: key, is_visible, icon } = d;
					return {
						path,
						component: () => import(/* @vite-ignore */`../views/${component}.vue`),
						name,
						meta: {
							title,
							key,
							icon,
							hidden: is_visible === 1 ? false : true
						}
					};
				});

				routes.push(route);
			}
			routes.push({
				path: '/:pathMatch(.*)*', redirect: '/404', meta: {
					hidden: true
				}
			});

			this.routes = constRoutes.concat(routes);
		}
	}
})